/**
 * Created by JLB1 on 2017/1/20.
 */
import React, {Component, PropTypes} from 'react'
import ReactDOM from "react-dom"
import { addErrorListener } from "../../lib/handleError"
import weixinShare from '../../lib/weixinShare';
import AJAX from "../../lib/ajax"
import Tools from "../../lib/tools"
import Rules from '../../lib/rules'
import Toast from '../MyPackage/components/Toast'

require('../../lib/rem')
require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('../../styles/lux.less');
require('./ReplacePhone.less');
class ReplacePhone extends Component {
    constructor(props) {
        super(props);
        this.state = {
            codeStateText: '发送验证码',
            time: 60,//倒计时
            isSend: false,//是否发送验证码
            isTimeOver: false,//60s倒计时结束

            phoneNum: '',//手机号
            phoneError: false,//手机号是否错误
            phoneTrue: false,//手机号填写正确

            pcode: '',//手机验证码
            pcodeError: false,//手机验证码是否正确
            pcodeText: '',//手机验证码错误内容

            twoCodeShow: false,//是否显示二次验证码
            twoCode: '',//生成的二次验证码
            localTwoCode: '',//填写的二次验证码
            twoCodeError: false,//二次验证码是否错误

            bindphone: ''

        };
        this.receivePcode = this.receivePcode.bind(this);
        this.setTime = this.setTime.bind(this);
        this.handleChangePhone = this.handleChangePhone.bind(this);
        this.handleChangePcode = this.handleChangePcode.bind(this);
        this.toBindPhone = this.toBindPhone.bind(this);
        this.receivePcodeFromService = this.receivePcodeFromService.bind(this);
        this.getTwoCode = this.getTwoCode.bind(this);
        this.handleChangeTwoCode = this.handleChangeTwoCode.bind(this)


    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll()
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
        AJAX.request("user_home", {}, (data) => {
            if (data.code === 0) {
                this.setState({
                    bindphone: data.body.phone
                })
            }
        });

        //如果是从短信获取验证码进来,重新获取验证码
        if (Tools.getParams().nopcode) {
            if (!Rules.phone(Tools.getParams().nopcode)) {
                this.setState({
                    phoneError: true,
                });
                return
            } else {
                this.setState({
                    phoneError: false
                })
            }
            const voice_verify = Tools.getParams().voice_verify;
            console.log('电话还是短信',voice_verify)
            //获取验证码
            let ismore = false
            AJAX.request("send_pcode", {phone: Tools.getParams().nopcode,voice_verify:voice_verify}, (data) => {
                //设置一分钟过期时间cookie
                //成功不成功都设置1分钟cookie
                if(data.code === 20011){
                    Toast.warn({
                        content: "验证码太频繁"
                    });
                    ismore = true
                    return
                }
                ismore = false
                let now = new Date();
                Tools.createCookie("JLB_rebindphone", this.state.phoneNum, now.getTime() / 1000, 60);
            });
            if(ismore){
                return
            }
            //开始倒计时
            this.timer = setInterval(this.setTime, 1000);
            this.setState({isSend: true, isTimeOver: false, phoneNum: Tools.getParams().nopcode,});
            return
        }
        //如果cookie 里面有发送手机号验证
        if (Tools.readCookie('JLB_rebindphone')) {
            //开启倒计时
            this.timer = setInterval(this.setTime, 1000);
            //设置初始状态
            this.setState({
                phoneNum: Tools.readCookie('JLB_rebindphone'),
                isSend: true,
                isTimeOver: false
            })
        }

    }

    //获取验证码按钮点击
    receivePcode() {

        //如果正在发送，阻止再次发送
        if (this.state.isSend) {
            return
        }
        //判断手机号是否正确
        if (!Rules.phone(this.state.phoneNum)) {
            this.setState({
                phoneError: true,
            });
            return
        } else {
            this.setState({
                phoneError: false
            })
        }
        //获取验证码
        this.receivePcodeFromService();

        //开始倒计时
        this.timer = setInterval(this.setTime, 1000);
        this.setState({isSend: true, isTimeOver: false})
    }

    //获取手机验证码
    receivePcodeFromService() {
        let ismore = false
        AJAX.request("send_pcode", {phone: this.state.phoneNum}, (data) => {
            //设置一分钟过期时间cookie
            //成功不成功都设置1分钟cookie
            if(data.code ===20011){
                Toast.warn({
                    content: "验证码太频繁"
                });
                ismore = true
                return
            }else {
                ismore = false
            }
            let now = new Date();
            Tools.createCookie("JLB_rebindphone", this.state.phoneNum, now.getTime() / 1000, 60);
        });
        if(ismore){
            return false
        }
    }


    //倒计时
    setTime() {
        //如果倒计时===1，重新发送
        if (this.state.time === 1) {
            this.setState({
                time: 60,
                codeStateText: '重新发送',
                isSend: false,
                isTimeOver: true,
                twoCodeShow: true,//显示二次验证码
            });
            this.getTwoCode();//过去二次验证码
            clearInterval(this.timer);//清空定时器
            return
        } else {
            this.setState({
                time: this.state.time -= 1,
                codeStateText: '(' + this.state.time + 's)秒后重新获取',
                isSend: true
            })
        }
    }

    //填写手机号
    handleChangePhone(e) {

        if (Rules.phone(e.target.value)) {
            this.setState({
                phoneNum: e.target.value,
                phoneTrue: true,
                phoneError: false

            })
        } else {
            this.setState({
                phoneNum: e.target.value,
                phoneTrue: false
            })
        }

    }

    //填写手机验证码
    handleChangePcode(e) {

        this.setState({
            pcode: e.target.value,
        });
        if (e.target.value.length == 6) {
            this.setState({
                pcodeError: false
            })
        }
    }

    //填写php验证码
    handleChangeTwoCode(e) {
        this.setState({
            localTwoCode: e.target.value
        })
    }

    //生成4位数验证码
    getTwoCode() {
        const twoCode = parseInt(Math.random() * (9999 - 1000 + 1) + 1000, 10);
        this.setState({
            twoCode: twoCode
        })
    }

    //提交绑定手机号
    toBindPhone() {
        //判断手机号
        if (!Rules.phone(this.state.phoneNum)) {
            this.setState({
                phoneError: true
            });
            return
        }
        //判断验证码
        if (!Rules.pcode(this.state.pcode)) {
            this.setState({
                pcodeError: true,
                pcodeText: '请输入6位手机验证码'
            });
            return
        }

        //判断如果有验证码，但是二次验证码填写错误
        if (this.state.twoCodeShow && this.state.twoCode != this.state.localTwoCode) {
            this.getTwoCode();//重新生成验证码，给出提示
            this.setState({
                twoCodeError: true,
                localTwoCode: '',
            });
            return
        }

        AJAX.request("rebind_phone", {phone: this.state.phoneNum, pcode: this.state.pcode}, (data) => {
            switch (data.code) {
                case 20010:
                    this.setState({
                        pcodeError: true,
                        pcodeText: data.msg,
                        pcode: ''
                    });
                    break;
                case 20022:
                    Tools.eraseCookie('JLB_rebindphone');
                    window.localStorage.removeItem('JLB_bindphoneErrmsg');
                    window.localStorage.setItem('JLB_bindphoneErrmsg', JSON.stringify(data.msg));
                    window.location.href = './BindPhoneError';
                    break;
                case 0:
                    Tools.eraseCookie('JLB_rebindphone');
                    window.location.href = './BindPhoneSuccess?phone=' + data.body
                    break;
                default :
                    alert(data.msg);
                    break;
            }

        })

    }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    render() {
        let phone = this.state.bindphone;
        let phoneShow = phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
        return (
            <div className="BindPhone_bg">
                <div className="doneBind">
                    <span> 您已经绑定的手机号：</span><span className="phone">{phoneShow}</span>
                </div>
                <div className="input_box">
                    <input className="weui-input" value={this.state.phoneNum} onChange={this.handleChangePhone}
                           type="number" pattern="[0-9]*"
                           placeholder="请输入手机号"/>
                    {
                        this.state.phoneTrue &&
                        <i className="iconfont icon-duigou phoneSuccess"/>
                    }

                </div>
                {
                    this.state.phoneError &&
                    <p className="dangerous"><i className="iconfont icon-iconfontjinggao"/>手机号格式错误</p>
                }

                <div>
                    {
                        this.state.twoCodeShow &&
                        <div className="input_box">
                            <input value={this.state.localTwoCode} onChange={this.handleChangeTwoCode} type="number"
                                   className="weui-input" pattern="[0-9]*"
                                   placeholder="请输入验证码"/>
                            <img onClick={this.getTwoCode}
                                 src={'/user/captcha/' + this.state.twoCode}
                                 alt=""/>
                        </div>
                    }

                    {
                        this.state.twoCodeError &&
                        <p className="dangerous"><i className="iconfont icon-iconfontjinggao"/>验证码错误</p>
                    }


                </div>


                <div className="input_box">
                    <input className="weui-input" onChange={this.handleChangePcode} value={this.state.pcode}
                           placeholder="请输入手机验证码" type="number"  pattern="[0-9]*" />
                    <div className="pcode" onClick={this.receivePcode}>
                        {this.state.codeStateText}
                    </div>
                </div>
                {
                    this.state.pcodeError &&
                    <p className="dangerous"><i className="iconfont icon-iconfontjinggao"/>{this.state.pcodeText}</p>
                }

                {
                    this.state.isSend && !this.state.isTimeOver &&
                    <p className="pcodeISSend">验证码已发送，120S内有效</p>
                }
                {
                    this.state.isTimeOver &&
                    <a href={"./NoPcode?nopcode=" + this.state.phoneNum + '&cburi=ReplacePhone'} className="noCode"><i
                        className="iconfont icon-iconfontjinggao noCodeIcon"/>收不到验证码?</a>
                }
                <div className="weui-btn-area">
                    <a className="weui-btn weui-btn_yellow" href="javascript:" onClick={this.toBindPhone}>绑定账号</a>
                </div>

            </div>
        )
    }
}
ReactDOM.render(<ReplacePhone />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}

